var table;
//相关业务逻辑
$(function(){
	orderProcedure.bind();
	orderProcedure.getOrderProcedure();
	orderProcedure.getAllTemp();
	orderProcedure.removeBtnBind();
	orderProcedure.remove();
//	nameToIdUtil.getProductionDepartment("productionDepartment");
//	nameToIdUtil.getProductionDepartment("productionDepartmentAdd");
	$("#orderProcedureDetail").hide();
});


var orderProcedure={//页面总变量
		orderId:"",
		addType:0,
		bind:function(){
			$("#productionDepartmentAdd").bind("change",function(){
				var deptId=$("#productionDepartmentAdd").val();
				nameToIdUtil.getWorkShopNameAndId("workShopAdd",deptId);
			});
			
			
			$("#tempSelect").bind("change",function(){
				var tempId=$(this).val();
				orderProcedure.getTempWorkShop(tempId);
			});
			
			
		    $("#setOrderSortModalBtn").bind("click",function(){
		    	var sort=$("#orderSortInput").val();
		    	var orderId=$("#sortModalOrderId").val();
		    	orderProcedure.setOrderSort(orderId,sort);
		    });
			
			$("#orderSortInput").bind("keyup",function(){
				inputUtil.inputNumberFu("orderSortInput");
			});
			
			$("#FuzzyBtn").bind("click",function(){
				var fuzzy=$("#FuzzyInput").val();
				var workShop=$("#workShop").val();
				orderProcedure.getAllWorkShopAndProcedure(fuzzy,workShop,0);
			});
			
			$("#FuzzyBtnAdd").bind("click",function(){
				var fuzzy=$("#FuzzyInputworkShopAdd").val();
				var workShop=$("#workShopAdd").val();
				orderProcedure.getOrderNoHaveProcedure(workShop,fuzzy);
			});
			
			
			$("#workShop").bind("change",function(){
				var workShop=$(this).val();
				$("#FuzzyInput").val("");
				orderProcedure.getAllWorkShopAndProcedure("",workShop,0);
			});
			
			$("#workShopAdd").bind("change",function(){
				var workShop=$(this).val();
				$("#FuzzyInputAdd").val("");
				orderProcedure.getOrderNoHaveProcedure(workShop,"");
			});
			
			$("#findOrder").bind("click",function(){
				orderProcedure.getOrderProcedure();
			});
			
			$("#addModalBtn").bind("click",function(){
				orderProcedure.addType=1;
				var procedureArray=new Array();
				var i=1;
				$(".right-box-add").find(".ui-sortable-handle").each(function(){
					var pro=new Object();
					pro.workshopName=$(this).attr("value");
					pro.processName=$(this).attr("data-id");
					pro.sort=i;
					procedureArray.push(pro);
					i++;
				});
				
				if(procedureArray.length<=0){
					layAlert("请选择工序");
					return false;
				}
				ajaxUtil.ajaxRuquest("orderProcedureTemplate/addOrderProcedure",{"procedureArray":JSON.stringify(procedureArray),"orderId":orderProcedure.orderId,"addType":orderProcedure.addType},function(data){
					layer.msg(data,{icon:1});
					table.ajax.reload( null, false);
					$("#addTemplateModal").modal("hide");
				});
			});
			
			
			$("#addModalCapyBtn").bind("click",function(){
				orderProcedure.addType=0;
				var procedureArray=new Array();
				var i=1;
				$(".right-box").find(".item").each(function(){
					var pro=new Object();
					pro.workshopName=$(this).attr("value");
					pro.processName=$(this).attr("data-id");
					pro.sort=i;
					procedureArray.push(pro);
					i++;
				});
				
				if(procedureArray.length<=0){
					layAlert("请选择工序");
					return false;
				}
				ajaxUtil.ajaxRuquest("orderProcedureTemplate/addOrderProcedure",{"procedureArray":JSON.stringify(procedureArray),"orderId":orderProcedure.orderId,"addType":orderProcedure.addType,"type":"create"},function(data){
					layer.msg(data,{icon:1});
					table.ajax.reload( null, false);
					$("#addTemplateCapyModal").modal("hide");
				});
			});
			
			
			$("#selectTempModalBtn").bind("click",function(){
				var tempId=$("#tempSelect option:selected").val();
				var workshopIdArray=new Array();
				$("input[name='checkWorkshop']:checked").each(function(){
					workshopIdArray.push($(this).val());
				});
				if(tempId==""){
					layAlert("请选择模板");
					return false;
				}
				if(workshopIdArray.length<=0){
					layAlert("请选择车间");
					return false;
				}
				ajaxUtil.ajaxRuquest("orderProcedureTemplate/addOrderProcedureByTemp",{"tempId":tempId,"orderId":orderProcedure.orderId,"workshopIdArray":JSON.stringify(workshopIdArray)},function(data){
						layer.msg(data,{icon:1});
						table.ajax.reload( null, false);
						$("#selectTempModal").modal("hide");
			    });
			});
			//选择工序
			$('#orderProcedureTable tbody').on('click', '.selectProcedure', function () {
				orderProcedure.addType=0;
				orderProcedure.orderId=$(this).val();
				var deptId=$(this).parent().children("input[type='hidden']").eq(0).val();
				if(deptId=='' || deptId == null){
					layAlert("该订单未设置部门");
					return false;
				}
				addOrder=$(this).val();
			    $("#productionDepartment").val(deptId);
			    nameToIdUtil.getWorkShopNameAndId("workShop",deptId);
			    orderProcedure.getAllWorkShopAndProcedure("","",1);
				$("#addTemplateCapyModal").modal("show");
			});
			
			//选择模板
			$('#orderProcedureTable tbody').on('click', '.selectTemplate', function () {
				orderProcedure.orderId=$(this).val();
				$("#selectTempModal").modal("show");
			});
			
			//添加工序
			$('#orderProcedureTable tbody').on('click', '.addProcedure', function () {
				orderProcedure.addType=1;
				orderProcedure.orderId=$(this).val();
				var deptId=$(this).parent().children("input[type='hidden']").eq(0).val();
				if(deptId=='' || deptId == null){
					layAlert("该订单未设置部门");
					return false;
				}
				addOrder=$(this).val();
			    $("#productionDepartmentAdd").val(deptId);
			    nameToIdUtil.getWorkShopNameAndId("workShopAdd",deptId);
				orderProcedure.getOrderNoHaveProcedure("","");
				orderProcedure.getOrderHaveProcedure(orderProcedure.orderId);
				
				$("#addTemplateModal").modal("show");
			});
			
			//导出为excle
			$('#orderProcedureTable tbody').on('click', '.exportExcle', function () {
				var orderId=$(this).val();
				var url="orderProcedureTemplate/downlodeOrderProcedure?orderId="+orderId;
				tableUtil.download(url);
			});
			
			//另存为模板
			$('#orderProcedureTable tbody').on('click', '.saveTemplate', function () {
				var orderId=$(this).val();
				layer.prompt({title: '请输入模板名称', formType: 2}, function(text, index){
					ajaxUtil.ajaxRuquest("orderProcedureTemplate/saveTemplateByOrderProcedure",{"orderId":orderId,"name":text},function(data){
						layer.msg(data,{icon:1});
					});
				});
			});
			
			//查看以报工详情
			$('#orderProcedureTable tbody').on('click', '.aleradyReport', function () {
				var procedureId=$(this).val();
				var orderId=$(this).parent().next().children(".remove ").val();
				var workShop=$(this).prevAll(".workShop").eq(0).val();
				ajaxUtil.ajaxRuquest("orderProcedureTemplate/getProcedureReport",{"procedureId":procedureId,"orderId":orderId,"workShop":workShop},function(data){
					if(data.length>0){
						var html="";
						for(var i=0;i<data.length;i++){
							html+="<tr><td>"+data[i].machining+"</td><td>"+data[i].color+"</td><td>"+data[i].qualified+"</td><td>"+data[i].touchTime+"</td></tr>";
						}
						$("#porpBody").html(html);
						$("#reportModal").modal("show");
					}
				});
			});
			
			
			//查看详情
			$('#orderProcedureTable tbody').on('click', '.seeDetail', function () {
				var orderId=$(this).val();
				window.location.href="shengChanModal.jsp?orderId="+orderId; 
			});
			
			
			//点击移除按钮
			$('#orderProcedureTable tbody').on('click', '.remove', function () {
				var text=$(this).text();
				if(text=="移除工序"){
					$(this).parents().children('td').children('.deleteX').show();
					$(this).text("完成");
				}else{
					$(this).parents().children('td').children('.deleteX').hide();
					$(this).text("移除工序");
				}
			});
			
			
			//点击x
			$('#orderProcedureTable tbody').on('click', '.deleteX', function () {
				var rowIdex= $(this).parent()[0]._DT_CellIndex.row; 
				var orderId=$(this).parents().children('td').children('.remove').val();
				var procedureId=$(this).attr("value");
				ajaxUtil.ajaxRuquest("orderProcedureTemplate/removeOrderProcedure",{"orderId":orderId,"procedureId":procedureId},function(data){
					layer.msg(data,{icon:1});
				    table.ajax.reload(function(data){
				    	table.rows().nodes().flatten().to$().eq(rowIdex).children('td').children('.deleteX').show();
				    	table.rows().nodes().flatten().to$().eq(rowIdex).children('td').children('.remove').text("完成");
				    }, false);
				});
			});
			
			//设置订单生产顺序
			$('#orderProcedureTable tbody').on('click', '.setSort', function () {
				var orderId=$(this).val();
				var sort=$(this).parent().parent().children("td").eq(0).text();
				$("#orderSortInput").val(sort);
				$("#sortModalOrderId").val(orderId);
				$("#setSortModal").modal("show");
			});
			
			//鼠标经过工序
			$('#orderProcedureTable tbody').on('click', '.tip', function () {
				var procedureId=$(this).val();
				var orderId=$(this).parent().next().children(".remove ").val();
				var workShop=$(this).prevAll(".workShop").eq(0).val();
				ajaxUtil.ajaxRuquest("expectDate/getProcedureExpectDate",{"orderId":orderId,"procedureId":procedureId,"workShop":workShop},function(data){
					layAlert("预计生产日期："+data);
					$(this).attr("data-tipso",data);
				});
			});
		},
		checkBind:function(){
			$(".workShopCheck").bind("click",function(){
				var name=$(this).attr("name");
				var is=$(this).is(":checked");
				if(is){
					$("input[name='proce"+name+"']").prop("checked",true); 
				}else{
					$("input[name='proce"+name+"']").prop("checked",false); 
				}
			});
			
			$(".proceCheck").bind("click",function(){
				var name=$(this).attr("name");
				var fatherName=name.substring(5,name.length);
				var length=$("input[name='"+name+"']").length; 
				var checkLength=$("input[name='"+name+"']:checked").length; 
				if(length==checkLength){
					$("input[name='"+fatherName+"']").prop("checked",true); 
				}else{
					$("input[name='"+fatherName+"']").prop("checked",false)
				}
			});
		},
		getOrderProcedure:function(){
			$("#orderProcedureDetail").hide();
			$("#orderProcedureTable").show();
			var orderId=$("#inputOrderId").val();
			table=ajaxUtil.dataTablesAjaxNotFxiaction("orderProcedureTable",5,"orderProcedureTemplate/getOrderRealProcedure",
//					table=ajaxUtil.dataTablesAjax("orderProcedureTable",5,"orderProcedureTemplate/getOrderRealProcedure",
					{"orderId":orderId},[
//					{"data":"name"},
					{"data":"sort"},
					{"data":"companyOrderId",render: function (data,type,row){
						return data+"<br/><hr/>"+row.factoryId+"<br/><hr/>"+row.customOrderId;
					}},
					{"data":"workShopList",render: function (data){
						var html="";
						for(var i=0;i<data.length;i++){
							var processList=data[i].processList;
							if(i>0){
								html+="<br/><br/>";
							}
							html+="<button class='btn btn-danger radius pad workShop' value='"+data[i].id+"'>"+data[i].workshopName+"</button> &nbsp;"
							for(var j=0;j<processList.length;j++){
								if(processList[j].isReport=="1"){
									html+="<button class='btn btn-success radius pad aleradyReport ' value='"+processList[j].id+"' >"+processList[j].processName+"</button>&nbsp;"
								}else if(processList[j].isReport=="2"){
									html+="<button class='btn btn-warning radius pad aleradyReport ' value='"+processList[j].id+"' >"+processList[j].processName+"</button>&nbsp;"
								}else{
									html+="<button class='btn radius pad tip' value='"+processList[j].id+"' >"+processList[j].processName+"</button><i class='deleteX Hui-iconfont' hidden='hidden'  value='"+processList[j].id+"'>&#xe60b;</i>&nbsp;"
								}
							}
						}
						return html;
					}},
					{"data":"name",render: function (data,type,row) {
						var list=row.workShopList;
						if(list<=0){
							return "<button class='selectTemplate btn btn-primary radius ' type='button' value='"+data+"' >选择模板</button> <br/><br/>" +
							 "<button value='"+data+"'  class='selectProcedure btn btn-primary radius '>选择工序</button><br/><br/>"+
							 "<input type='hidden' value='"+row.deptId+"'  class='OrderDeptId'/>"+
							 "<button value='"+data+"'  class='setSort btn btn-primary radius '>设置生产顺序</button>";
						}else{
							return "<button class='selectTemplate btn btn-primary radius ' type='button' value='"+data+"' >选择模板</button> <br/><br/>"+
							       "<button value='"+data+"'  class='addProcedure btn btn-primary radius '>添加工序</button><br/><br/>"+
						 	       "<button value='"+data+"'  class='seeDetail btn btn-primary radius '>查看详情</button><br/><br/>" +
						 	       "<button value='"+data+"'  class='saveTemplate btn btn-primary radius '>存为模板</button><br/><br/>" +
						 	       "<button value='"+data+"'  class='remove btn btn-primary radius '>移除工序</button><br/><br/>" +
							       "<button value='"+data+"'  class='setSort btn btn-primary radius '>设置生产顺序</button><br/><br/>"+
							       "<input type='hidden' value='"+row.deptId+"'  class='OrderDeptId'/>"+
						      	   "<button value='"+data+"'  class='exportExcle btn btn-primary radius '>导出为excel</button>";
						}
					}}
			]
		  );
		},
		//获取所有车间下的所有工序
		getAllWorkShopAndProcedure:function(fuzzy,workShop,type){
			$(".left-box").html("");
			if(type!=0){
			    $(".right-box").html("");
			}
			var procedureArray=new Array();
			$(".right-box").find(".item").each(function(){
				var processName=$(this).attr("data-id");
				procedureArray.push(processName);
			});
			var deptId=$("#productionDepartment").val();
			ajaxUtil.ajaxRuquest("orderProcedureTemplate/getAllWorkShopAndProcedure",{"type":0,"workShop":workShop,"fuzzy":fuzzy,'deptId':deptId},function(data){
				var html="";
				for(var i=0;i<data.length;i++){
					var proceList=data[i].processList;
					var workId=data[i].id;
					var workName=data[i].workshopName;
					for(var j=0;j<proceList.length;j++){
						if($.inArray(proceList[j].id,procedureArray)<0){
							html+="<li class='item ui-sortable-handle' value='"+workId+"' data-id="+proceList[j].id+">"+workName +"&nbsp;"+proceList[j].processName+"</li>"
						}
					}
					html+="<br/>";
				}
				$(".left-box").append(html);
				orderProcedure.leftAndRightBind();
			});
		},
		getAllTemp:function(){
			ajaxUtil.ajaxRuquest("orderProcedureTemplate/getAllTemp",null,function(data){
				var html="";
				for(var i=0;i<data.length;i++){
					html+="<option value='"+data[i].id+"'>"+data[i].name+"</option>";
				}
				$("#tempSelect").append(html);
			});
		},
		getOrderHaveProcedure:function(orderId){
			ajaxUtil.ajaxRuquest("orderProcedureTemplate/getOrderProcedureDetail",{"orderId":orderId},function(data){
				var html="";
				for(var i=0;i<data.length;i++){
						html+="<li class=' ui-sortable-handle' value='"+data[i].workshopId+"' data-id="+data[i].id+">"+data[i].workshopName +"&nbsp;"+data[i].processName+"</li>"
				}
				$(".right-box-add").html("");
				$(".right-box-add").append(html);
			});
		},
		getOrderNoHaveProcedure:function(workShop,fuzzy){
			var procedureArray=new Array();
			var deptId=$("#productionDepartmentAdd").val();
			$(".right-box-add").find(".ui-sortable-handle").each(function(){
				var processName=$(this).attr("data-id");
				procedureArray.push(processName);
			});
			ajaxUtil.ajaxRuquest("orderProcedureTemplate/getAllWorkShopAndProcedure",{"type":2,"orderId":orderProcedure.orderId,"workShop":workShop,"fuzzy":fuzzy,'deptId':deptId},function(data){
				var html="";
				if(data.length<=0){
					html="<li>该车间没有没添加的工序</li>";
				}
				for(var i=0;i<data.length;i++){
					var proceList=data[i].processList;
					var workId=data[i].id;
					var workName=data[i].workshopName;
					for(var j=0;j<proceList.length;j++){
						if($.inArray(proceList[j].id, procedureArray)<0){
							html+="<li class='item ui-sortable-handle' value='"+workId+"' data-id="+proceList[j].id+">"+workName +"&nbsp;"+proceList[j].processName+"</li>"
						}
					}
					html+="<br/>";
				}
				$(".left-box-add").html("");
				$(".left-box-add").append(html);
				orderProcedure.addLeftAndRightBind();
			});
		},
		addLeftAndRightBind:function(){
			$(".item").unbind("click");
			$(".left-box-add .item").unbind("dblclick");
			$(".right-box-add .item").unbind("dblclick");
			//单击
			$(".item").bind("click",function(){
				$(this).toggleClass("selected-item");
			});
			
			//左边双击右移
			$(".left-box-add .item").bind("dblclick",function(){
				$(".right-box-add").append($(this).removeClass('selected-item'));
				orderProcedure.addLeftAndRightBind();
			});
			
            //右边双击左移
			$(".right-box-add .item").bind("dblclick",function(){
				$(".left-box-add").append($(this).removeClass('selected-item'));
				orderProcedure.addLeftAndRightBind();
			});
		},
		leftAndRightBind:function(){
			$(".item").unbind("click");
			$(".left-box .item").unbind("dblclick");
			$(".right-box .item").unbind("dblclick");
			//单击
			$(".item").bind("click",function(){
				$(this).toggleClass("selected-item");
			});
			
			//左边双击右移
			$(".left-box .item").bind("dblclick",function(){
				$(".right-box").append($(this).removeClass('selected-item'));
				orderProcedure.leftAndRightBind();
			});
			
            //右边双击左移
			$(".right-box .item").bind("dblclick",function(){
				$(".left-box").append($(this).removeClass('selected-item'));
				orderProcedure.leftAndRightBind();
			});
		},
		removeBtnBind:function(){
			$(".add-one").bind("click",function(){
				$(".right-box").append($(".left-box").find('.selected-item').removeClass('selected-item'));
			});
			
			$(".add-all").bind("click",function(){
				$(".right-box").append($(".left-box").find('.item').removeClass('selected-item'));
			});
			
			$(".remove-one").bind("click",function(){
				$(".left-box").append($(".right-box").find('.selected-item').removeClass('selected-item'));
			});
			
			$(".remove-all").bind("click",function(){
				$(".left-box").append($(".right-box").find('.item').removeClass('selected-item'));
			});
			
			$(".add-one-add").bind("click",function(){
				$(".right-box-add").append($(".left-box-add").find('.selected-item').removeClass('selected-item'));
			});
			
			$(".remove-one-add").bind("click",function(){
				$(".left-box-add").append($(".right-box-add").find('.selected-item').removeClass('selected-item'));
			});
		},
		//工序移动排序
		remove:function(){
			$('.item-box').sortable({
				placeholder: 'item-placeholder',
				connectWith: '.item-box',
				revert: true
			}).droppable({
				accept: '.item',
				hoverClass: 'item-box-hover',
				drop: function(event, ui){
					setTimeout(function(){
						ui.draggable.removeClass('selected-item');
					}, 500);
				}
			}).disableSelection();
		},
		//设置订单生产顺序
		setOrderSort:function(orderId,sort){
			if(Number(sort)<0){
				sort=-2;
			}
			ajaxUtil.ajaxRuquest("orderProcedureTemplate/setOrderSort",{"orderId":orderId,"sort":sort},function(data){
				 layer.msg(data,{icon:1});
				 $("#setSortModal").modal("hide");
				 table.ajax.reload(null, false);
			});
		},
	    //获取模板车间
		getTempWorkShop:function(tempId){
			ajaxUtil.ajaxRuquest("orderProcedureTemplate/getTempWorkShop",{"tempId":tempId},function(data){
				var html="<br/>";
				for(var i=0;i<data.length;i++){
					html+="&nbsp;&nbsp;&nbsp;<input type='checkbox' value='"+data[i].id+"' name='checkWorkshop'>"+data[i].workshopName;
				}
				$("#checkDiv").html(html);
			});
		}
}

//setInterval ("table.ajax.reload(null, false)", 1000);//十五分钟更新一次数据
